<?php


namespace App\Model\Finance;


use App\Model\CacheTable;
use App\Model\DataTable;
use App\Model\User;
use App\Utility\FinanceUtil;
use App\Utility\Pool\MysqlPool;
use App\Utility\Pool\RedisPool;
use EasySwoole\Utility\Random;

class Util
{

    public static function score()
    {
        $redisPool = RedisPool::defer();
        $db = MysqlPool::defer();
        //初始化
        //总分
        $totalscore = $db->where('status', '竞猜中')
            ->sum(DataTable::GUESS_TABLE, 'score');

        //百分比
        $win = $db->where('status', '竞猜中')
            ->where('beat', 1, '=')
            ->sum(DataTable::GUESS_TABLE, 'score');

        $t = 50;
        if ($totalscore != 0) {
            $t = intval(($win / $totalscore) * 100);
        }

        if ($t == 100) {
            $t -= rand(15, 30);
        }
        if ($t == 0) {
            $t += rand(15, 30);
        }

        $dataScore['type'] = 'datascore';
        $dataScore['score'] = intval($totalscore);
        $dataScore['percent'] = $t;
        $redisPool->set('cz_score_total_cache', json_encode($dataScore));
        return $dataScore;
    }

    public static function robotInit()
    {
        $db = MysqlPool::defer();
        self::score();
        //每5秒向所有用户发送一条信息
        return $db->get('cz_user_bot', [rand(300, 5000), 300], 'avatar');

    }

    public static function redpackInit($falg = true)
    {
        if ($falg) {
            $c_1 = CacheTable::getRedPack('1');
            $c_5 = CacheTable::getRedPack('5');
            $c_q = CacheTable::getRedPack('rqcode');
            if ($c_1 == 0 && $c_5 == 0 && $c_q == 0) {
                //初始化
                CacheTable::setRedPack('1', CacheTable::getFinanceConfig()['RED_PACK_1']);
                CacheTable::setRedPack('5', CacheTable::getFinanceConfig()['RED_PACK_5']);
                CacheTable::setRedPack('rqcode', CacheTable::getFinanceConfig()['RQCODE_COUNT']);
            }
        } else {
            CacheTable::setRedPack('1', CacheTable::getFinanceConfig()['RED_PACK_1']);
            CacheTable::setRedPack('5', CacheTable::getFinanceConfig()['RED_PACK_5']);
            CacheTable::setRedPack('rqcode', CacheTable::getFinanceConfig()['RQCODE_COUNT']);
        }

    }


    public static function getSignin($uid)
    {
        $redis = RedisPool::defer();
        $data = json_decode($redis->get(CacheTable::SIGNIN_CACHE . $uid), true);
        //$data = NULL;
        if ($data === NULL) {
            /*
            $ex = $redis->ttl(CacheTable::SIGNIN_CACHE.$uid);
            var_dump($data);
            var_dump($ex);
             */
            $db = MysqlPool::defer();
            //取今天
            $count = $db
                ->where('user_id', $uid)
                ->where('date_str', date('Ymd'))
                ->where('memo', '签到', '=')
                ->count(DataTable::SCORE_LOG_TABLE);
            if ($count > 0) {
                $data['is_signin'] = false;
            } else {
                $data['is_signin'] = true;
            }
            //取昨天
            $yesterday = date("Ymd", strtotime(date("Y-m-d")) - 86400);
            $yes_count = $db
                ->where('user_id', $uid)
                ->where('date_str', $yesterday)
                ->where('memo', '签到')
                ->count(DataTable::SCORE_LOG_TABLE);

            //找连签记录
            $user = $db->where('id', $uid, '=')
                ->getOne(DataTable::USER_TABLE, null, 'nickname,score,signin_time');

            $data['nickname'] = $user['nickname'];
            if ($yes_count > 0) {
                $data['signin_time'] = $user['signin_time'];
                if ($user['signin_time'] == 5 && $data['is_signin']) {
                    $data['signin_time'] = 0;
                }
                if ($user['signin_time'] > 1 && $user['score'] > 115) {
                    //查最近有没竞猜
                    $beg = FinanceUtil::lastTradeDayTime() - 32400;
                    $now = time();
                    $guesscount = $db->where('user_id', $uid)
                        ->whereBetween('createtime', [$beg, $now])
                        ->count(DataTable::GUESS_TABLE);
                    if ($guesscount > 0) {
                        $data['is_signin'] = true;
                    } else {
                        $data['is_signin'] = false;
                    }
                }


            } else {
                if ($data['is_signin']) {
                    $data['signin_time'] = 0;
                } else {
                    $data['signin_time'] = 1;
                }
            }
            $redis->set(CacheTable::SIGNIN_CACHE . $uid, json_encode($data), FinanceUtil::now2todayend());
        }

        return $data;
    }

    public static function isGuess($uid)
    {
        $redis = RedisPool::defer();
        $data = $redis->get(CacheTable::IS_GUESS_CACHE . $uid);
        if ($data == NULL || $data == '') {

            $db = MysqlPool::defer();
            /*
            $now = time();
            $beg = FinanceUtil::now2h15();
            $count = $db->where('user_id',$uid,'=')
                ->whereBetween('createtime',[$beg,$now])
                ->count(DataTable::GUESS_TABLE);
           */
            $count = $db->where('user_id', $uid, '=')
                ->where('status', '竞猜中')
                ->count(DataTable::GUESS_TABLE);
            if ($count > 0) {
                $data = 0;
            } else {
                $data = 1;
            }
            $redis->set(CacheTable::IS_GUESS_CACHE . $uid, $data, FinanceUtil::now2h15time());
        }
        return $data;
    }


    public static function isAppointment($uid)
    {
        $redis = RedisPool::defer();
        $data = $redis->get(CacheTable::IS_APPOINTMENT . $uid);

        if ($data == NULL || $data == '') {
            /*
            $ex = $redis->ttl(CacheTable::IS_APPOINTMENT.$uid);
            var_dump($data);
            var_dump($ex);*/
            $db = MysqlPool::defer();
            $count = $db->where('id', $uid, '=')
                ->where('msg_status', '1' . '=')
                ->count(DataTable::THIRD_TABLE);
            if ($count > 0) {
                $data = 0;
            } else {
                $data = 1;
            }
            $redis->set(CacheTable::IS_APPOINTMENT . $uid, $data, 2592000);
        }

        return $data;
    }

    public static function signin($uid, $ip)
    {
        $datacache = self::getSignin($uid);
        if ($datacache['is_signin'] == 0) {
            return ErrDec::SIGNIN_ERR;
        }

        $redis = RedisPool::defer();
        $key = 'signin_1_' . $uid;
        $op = $redis->get($key);
        if ($op) {
            return ErrDec::OPT_ERR;
        }
        $redis->set($key, 1, 5);

        $key = CacheTable::SIGNIN_IP_CONN_CACHE . '_' . $ip;
        $ip_count = intval($redis->get($key));
        if ($ip_count > CacheTable::getFinanceConfig()['IP_LIMIT_COUNT']) {

            return ErrDec::OPT_IP_ERR;
        }

        $isdeny = User::isDeny($uid);
        if ($isdeny) {
            return ErrDec::DENY_USER;
        }
        $datacache['signin_time']++;
        $ext_score = 0;
        $score = 15;
        if ($datacache['signin_time'] == 5) {
            $ext_score = rand(1, 15);
        }
        $db = MysqlPool::defer();
        $db->startTransaction();
        try {
            $ext['type'] = '签到';
            $ext['value'] = $datacache['signin_time'];
            User::score($db, $score + $ext_score, $uid, '签到', $ext);
            //记录签到IP时间
            $insterLog['user_id'] = $uid;
            $insterLog['ip'] = $ip;
            $insterLog['createtime'] = time();
            $db->insert(DataTable::SIGNIN_LOG, $insterLog);
            $db->commit();
        } catch (\Exception $e) {
            $db->rollback();
        }

        $ip_count++;
        $redis->set($key, $ip_count, 600);

        //重设一下缓存
        $datacache['is_signin'] = 0;
        $redis->set(CacheTable::SIGNIN_CACHE . $uid, json_encode($datacache), FinanceUtil::now2todayend());
        $res['is_signin'] = $datacache['is_signin'];
        $res['signin_time'] = $datacache['signin_time'];

        $res['score'] = $score;
        $res['ext_score'] = $ext_score;
        return [1, $res];

    }

    public static function guess($uid, $beat, $ip)
    {
        $beatarr = [0, 1];
        if (!in_array($beat, $beatarr)) {
            return ErrDec::OPT_IP_ERR;
        }

        if (!FinanceUtil::is_guess_time()) {
            return ErrDec::GUESS_TIME_ERR;
        }

        if (!self::isGuess($uid)) {
            return ErrDec::SUBMIT_ERR;
        }
        $score = 100;
        $redis = RedisPool::defer();
        $key = 'guess_1_' . $uid;
        $op = $redis->get($key);
        if ($op) {
            return ErrDec::OPT_ERR;
        }
        $redis->set($key, 1, 5);

        /**
         * $key = CacheTable::GUSEE_IP_CONN_CACHE.'_'.$ip;
         * $ip_count = intval($redis->get($key));
         * if($ip_count > CacheTable::getFinanceConfig()['IP_LIMIT_COUNT']){
         * return ErrDec::OPT_IP_ERR;
         * }*/

        $isdeny = User::isDeny($uid);
        if ($isdeny) {
            return ErrDec::DENY_USER;
        }


        $db = MysqlPool::defer();
        $count = $db->where('user_id', $uid)
            ->where('status', '竞猜中')
            ->count(DataTable::GUESS_TABLE);
        if ($count > 0) {
            return ErrDec::SUBMIT_ERR;
        }
        //查看是否够积分
        $scount = $db->where('id', $uid)
            ->where('score', 100, '>=')
            ->count(DataTable::USER_TABLE);
        if ($scount <= 0) {
            return ErrDec::GUESS_SCORE_ERR;
        }

        //添加竞猜
        $db->startTransaction();
        try {
            $beat_txt = '涨';
            if ($beat == 0) {
                $beat_txt = '跌';
            }

            User::score($db, -$score, $uid, '参与竞猜涨跌:' . $beat_txt);
            $insdata['user_id'] = $uid;
            $insdata['beat'] = $beat;
            $insdata['score'] = $score;
            $insdata['createtime'] = time();
            $insdata['updatetime'] = time();
            $insdata['date_str'] = FinanceUtil::nextTradeDay();
            $db->insert(DataTable::GUESS_TABLE, $insdata);
            //记录次数
            $win = $db->where('user_id', $uid)
                ->getOne(DataTable::FINANCE_SCORE_TABLE);
            if ($win) {
                $db->where('user_id', $uid)->setInc(DataTable::FINANCE_SCORE_TABLE, 'time');
            } else {
                $insterFinance['user_id'] = $uid;
                $insterFinance['createtime'] = time();
                $db->insert(DataTable::FINANCE_SCORE_TABLE, $insterFinance);
            }
            $db->commit();
        } catch (\Exception $e) {
            $db->rollback();
            return ErrDec::OPT_IP_ERR;
        }
        //设置一下缓存
        //$ip_count++;
        //$redis->set($key,$ip_count,600);
        $redis->set(CacheTable::IS_GUESS_CACHE . $uid, 0, FinanceUtil::now2h15time());
        $redis->delete(CacheTable::BEST_WINER_USER . $uid);
        return ErrDec::SUCCESS;

    }

    public static function pay($uid, $score, $ip)
    {
        //只能兑换 100 500 1000
        $pay_arr = [100, 500];

        if (!in_array($score, $pay_arr)) {
            return ErrDec::OPT_IP_ERR;
        }

        $redis = RedisPool::defer();
        $key = 'guess_1_' . $uid;
        $op = $redis->get($key);
        if ($op) {

            return ErrDec::OPT_ERR;
        }
        $redis->set($key, 1, 5);
        //判断ip
        $key = CacheTable::PAY_IP_CONN_CACHE . '_' . $ip;
        $ip_count = intval($redis->get($key));
        /*
        if($ip_count > (CacheTable::getFinanceConfig()['IP_LIMIT_COUNT']-3)){
            return ErrDec::PAY_ORDER_ERR;
        }*/

        if ($ip_count > 1) {
            return ErrDec::OPT_ERR;
        }


        $db = MysqlPool::defer();
        //判断这个用户是否已经提过现了
        $userinfo = $db->where('id', $uid)
            ->getOne(DataTable::USER_TABLE, 'id,score,jointime,freeze_score');
        if (!$userinfo) {
            return ErrDec::OPT_IP_ERR;
        }

        if ($userinfo['freeze_score'] > 0) {
            return ErrDec::PAY_ORDER_ERR;
        }

        if ($userinfo['score'] - $score < 100) {
            return ErrDec::PAY_SCORE_ERR;
        }
        if ($score >= 500) {

            if (time() - $userinfo['jointime'] < 259200) {
                return ErrDec::PAY_USER_ERR;
            }
            $count = $db->where('user_id', $uid)->count(DataTable::GUESS_TABLE);
            if ($count < 5) {
                return ErrDec::PAY_USER_ERR;
            }
        }


        $isdeny = User::isDeny($uid);
        if ($isdeny) {
            return ErrDec::DENY_USER;
        }
        $isguess = User::isGuessOnce($uid);
        if (!$isguess) {
            return ErrDec::PAY_GUESS_ONCE_ERR;
        }


        $is_ext = $db->where('user_id', $uid)
            ->whereLike('memo', '积分兑换:%')
            ->where('date_str', date('Ymd'))
            ->getOne(DataTable::SCORE_LOG_TABLE);
        if ($is_ext) {
            return ErrDec::PAY_ORDER_ERR;
        }

        /*
        $is_pay_once = $db->where('user_id',$uid)
            ->getOne(DataTable::ORDER_TABLE);

        if($is_pay_once){
            $count = $db->where('user_id',$uid)->count(DataTable::GUESS_TABLE);
            if($count < 5){
                return ErrDec::PAY_USER_ERR;
            }
        }
        */


        $db->startTransaction();
        try {
            $orderNo = date("YmdHis") . Random::number();
            //减用户的积分
            User::score($db, -$score, $uid, '积分兑换:' . $orderNo);
            //冻结积分
            $db->where('id', $uid)->setValue(DataTable::USER_TABLE, 'freeze_score', $score);

            //提交兑换申请
            $insdata['user_id'] = $uid;
            $insdata['paymount'] = $score;
            $insdata['createtime'] = time();
            $insdata['updatetime'] = time();
            $insdata['order_no'] = $orderNo;

            $db->insert(DataTable::ORDER_TABLE, $insdata);

            $db->commit();
            $ip_count++;
            $redis->set($key, $ip_count, 86400);
            return ErrDec::SUCCESS;
        } catch (\Exception $e) {
            $db->rollback();
            return ErrDec::OPT_IP_ERR;
        }

    }

    public static function payRQcode($uid)
    {
        $score = 1000;

        if ($score != 1000) {
            return ErrDec::OPT_IP_ERR;
        }

        $redis = RedisPool::defer();
        $key = 'guess_1_' . $uid;
        $op = $redis->get($key);
        if ($op) {
            return ErrDec::OPT_ERR;
        }
        $redis->set($key, 1, 5);


        $db = MysqlPool::defer();
        //判断这个用户
        $userinfo = $db->where('id', $uid)
            ->getOne(DataTable::USER_TABLE, 'id,score');
        if (!$userinfo) {
            return ErrDec::OPT_IP_ERR;
        }
        if ($userinfo['score'] - $score < 100) {
            return ErrDec::PAY_SCORE_ERR;
        }
        $isdeny = User::isDeny($uid);
        if ($isdeny) {
            return ErrDec::DENY_USER;
        }
        //判断这个用户今天有没兑换过
        $is_ext = $db->where('user_id', $uid)
            ->where('memo', '积分兑换进群二维码')
            ->where('date_str', date('Ymd'))
            ->getOne(DataTable::SCORE_LOG_TABLE);
        if ($is_ext) {
            return ErrDec::PAY_ORDER_ERR;
        }
        $db->startTransaction();
        try {
            //减用户的积分
            User::score($db, -$score, $uid, '积分兑换进群二维码');
            $db->commit();
        } catch (\Exception $e) {
            $db->rollback();
            return ErrDec::OPT_IP_ERR;
        }
        return ErrDec::SUCCESS;
    }

    public static function bestWin($uid)
    {
        $redis = RedisPool::defer();
        $key = CacheTable::BEST_WINER_USER . $uid;
        $data = json_decode($redis->get($key), true);
        if (!$data) {
            $db = MysqlPool::defer();
            $info = $db->where('user_id', $uid)
                ->getOne(DataTable::FINANCE_SCORE_TABLE, 'wintime,wincount,time,tjtime');
            if ($info) {
                $data['bestwin'] = $info['wintime'];
                if ($info['tjtime'] > 0) {
                    $data['present'] = number_format(($info['wincount'] / $info['tjtime']) * 100, 2);
                } else {
                    $data['present'] = 0;
                }
                $data['count'] = $info['time'];
            } else {
                $data['bestwin'] = 0;
                $data['present'] = 0;
                $data['count'] = 0;
            }

            $redis->set($key, json_encode($data), FinanceUtil::now2h15time());
        }
        return $data;
    }

    public static function ranking()
    {
        //取缓存
        $key = 'cz_score_best_winer_list';
        $redis = RedisPool::defer();
        $data = json_decode($redis->get($key), true);
        if (!$data) {
            $file_path = EASYSWOOLE_TEMP_DIR . '/score.data';
            $fp = fopen($file_path, "r");
            $str = fread($fp, filesize($file_path));
            $redis->set($key, $str, 604800);

        }

        if (!$data) {
            $data = array();
        }

        return $data;


    }

    public static function clean($uid)
    {
        $redis = RedisPool::defer();
        $redis->delete(CacheTable::IS_GUESS_CACHE . $uid);
        $redis->delete(CacheTable::SIGNIN_CACHE . $uid);
        $redis->delete(CacheTable::INVITE_USER_CACHE . $uid);
    }

    public static function cleanip($ip)
    {
        $redis = RedisPool::defer();
        $key = CacheTable::SIGNIN_IP_CONN_CACHE . '_' . $ip;
        $redis->delete($key);
        $key = CacheTable::GUSEE_IP_CONN_CACHE . '_' . $ip;
        $redis->delete($key);
        $key = CacheTable::PAY_IP_CONN_CACHE . '_' . $ip;
        $redis->delete($key);
    }

    public static function tradeDay()
    {
        $redis = RedisPool::defer();
        $key = 'cz_tradeday';
        $data = json_decode($redis->get($key), true);
        //$data = false;
        if (!$data) {
            $data['last'] = FinanceUtil::lastTradeDayTime();
            $data['next'] = FinanceUtil::nextTradeDayTime();
            $redis->set($key, json_encode($data), FinanceUtil::now2h15time());
        }

        return $data;
    }
}